// pages/dashboard/dashboard.js
Page({
  data: {
    currentYear: '',
    currentMonth: '',
    calendar: null,
    income: 0,
    expense: 0,
    balance: 0,
    chartData: {
      option: {
        textStyle: {
          color: '#333333'
        },
        xAxis: {
          axisLabel: {
            color: '#333333'
          }
        },
        yAxis: {
          axisLabel: {
            color: '#333333'
          }
        }
      }
    },
    records: []
  },
  onLoad() {
    const date = new Date();
    this.setData({
      currentYear: date.getFullYear(),
      currentMonth: date.getMonth() + 1
    });
    this.loadData();
  },
  onPullDownRefresh() {
    this.loadData();
    wx.stopPullDownRefresh();
  },
  onShow() {
    // 页面显示时重新加载数据
    this.loadData();
  },
  loadData() {
    const app = getApp();
    const records = app.globalData.records || [];
    
    // 计算收入、支出和结余
    let income = 0;
    let expense = 0;
    records.forEach(record => {
      const amount = Number(record.amount) || 0;
      if (record.type === 'income') {
        income += amount;
      } else if (record.type === 'expense') {
        expense += amount;
      }
    });
    
    this.setData({
      records: records,
      income: income.toFixed(2),
      expense: expense.toFixed(2),
      balance: (income - expense).toFixed(2)
    });
  },
  handleChartTap(e) {
    // 处理图表点击钻取
  },
  navigateToRecord() {
    wx.navigateTo({
      url: '/pages/record/record'
    })
  },
  handleRecordDelete(e) {
    const index = e.currentTarget.dataset.index;
    const app = getApp();
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.records.splice(index, 1);
          
          // 更新本地存储
          wx.setStorageSync('records', app.globalData.records);
          
          this.loadData();
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  }
});